<template>
  <div class="table-container pull-chheight">
    <el-form :model="formInline" class="demo-ruleForm" size="mini">
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="姓名" label-width="40px">
            <el-input v-model="formInline.user" placeholder="姓名或电话号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="分组" label-width="40px">
            <el-cascader change-on-select :options="groupTreeList" v-model="formInline.groupsort" @change="getGroupSourceNode">
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="6">
        <el-form-item label="来源渠道"  label-width="70px">
          <el-cascader :options="channelSourceTree" style="width: 100%;" v-model="formInline.channel" expand-trigger="hover" @change="getSourceNode">
          </el-cascader>
        </el-form-item>
        </el-col>
        <el-col :span="8">
        <el-form-item label="意向等级" label-width="70px">
          <el-select v-model="formInline.industryType" style="width: 500px;" multiple collapse-tags placeholder="请选择分组">
            <el-option style="width: 250px;" v-for="item in infoForm.intentionLevel" :key="item[1]" :label="item[0]"
                       :value="item[1]"></el-option>
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="5">
          <el-form-item label="标签" label-width="40px">
            <input type="hidden" v-model="formInline.label"/>
            <el-select v-model="selectLabel" collapse-tags placeholder="请选择" multiple @change="formLabel">
              <el-option-group v-for="group in labelData" :label="group.label" :key="group.label">
                <el-option v-for="item in group.children" :label="item.label" :key="item.label"
                           :value="item.value"></el-option>
              </el-option-group>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工作区域" label-width="70px">
            <el-select v-model="formInline.workingArea" multiple collapse-tags placeholder="请选择分组">
              <el-option v-for="item in infoForm.workingArea" :key="item[1]" :label="item[0]"
                         :value="item[1]"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <avue-crud :option="tableOption" v-model="user" :data="tableData" :table-loading="tableLoading"
               :page="listQuery" ref="crud" @row-save="handleSave" @size-change="handleSizeChange"
               @row-update="handleUpdate" :before-close="boxhandleClose" @row-dblclick="handleRowDBLClick"
               @row-del="handleDel" @refresh-change="handlerefreshChange" @current-change="handleCurrentChange"
               @search-change="handleSearchChange" @selection-change="handleSelectionChange"
               :row-class-name="tableRowClassName">
      <template slot="menuRight">
        <el-button v-if="qs_intention_customer_add" title="新增" type="primary" icon="el-icon-plus" @click="handleAdd"
                   circle size="small"></el-button>
        <el-button v-if="qs_intention_customer_upd" title="分组" type="primary" icon="el-icon-edit" @click="batchUpdate"
                   circle size="small"></el-button>
        <el-button v-if="qs_intention_customer_transfer" title="转移" type="primary" icon="el-icon-sold-out" circle size="small"
        @click="handleTransfer"></el-button>
        <el-button v-if="qs_intention_customer_followupList" title="跟进信息" type="info" icon="el-icon-tickets"
                   @click="handleCalls" circle size="small"></el-button>
      </template>
      <template slot-scope="scope" slot="groupsort">
        <span>{{ getGroupsort(scope.row.groupsort)}}</span>
      </template>
      <template slot-scope="scope" slot="groupsortForm">
        <el-cascader change-on-select :options="groupTreeList" v-model="groupsortDefault" @change="getGroupSourceNode">
        </el-cascader>
        <input type="hidden" v-model="user.groupsort"/>
      </template>
      <template slot-scope="scope" slot="channelForm">
        <el-cascader :options="channelSourceTree" v-model="defaultSource" expand-trigger="hover"
                     @change="getSourceNode">
        </el-cascader>
        <input type="hidden" v-model="user.channel"/>
      </template>
      <template slot-scope="props" slot="expand">
        <el-form label-position="left" inline class="demo-table-expand">
          <el-form-item label="姓名">
            <span>{{ props.row.fname }}</span>
          </el-form-item>
          <el-form-item label="手机号1">
            <span>{{ props.row.tel1 }}</span>
          </el-form-item>
          <el-form-item label="手机号2">
            <span>{{ props.row.tel2 }}</span>
          </el-form-item>
          <el-form-item label="微信">
            <span>{{ props.row.wechat }}</span>
          </el-form-item>
          <el-form-item label="身份证号">
            <span>{{ props.row.idCard }}</span>
          </el-form-item>
          <el-form-item label="行业类别">
            <span>{{ props.row.workingType}}</span>
          </el-form-item>
          <el-form-item label="职位">
            <span>{{ props.row.jobType }}</span>
          </el-form-item>
          <el-form-item label="工作区域">
            <span>{{ props.row.workingArea }}</span>
          </el-form-item>
          <el-form-item label="居住区域">
            <span>{{ props.row.homeArea }}</span>
          </el-form-item>
          <el-form-item label="居住地址">
            <span>{{ props.row.homeAddress }}</span>
          </el-form-item>
          <el-form-item label="收集时间">
            <span>{{ formatDate(props.row.collectDate, 'yyyy-MM-dd')}}</span>
          </el-form-item>
          <el-form-item label="来源渠道">
            <span>{{ props.row.channel }}</span>
          </el-form-item>
          <el-form-item label="意向等级">
            <span>{{ props.row.intentionLevel }}</span>
          </el-form-item>
          <el-form-item label="意向校区">
            <span>{{ setDicData(props.row.school)}}</span>
          </el-form-item>
          <el-form-item label="跟进人">
            <span>{{ userIdToName(props.row.followUpUser) }}</span>
          </el-form-item>
          <el-form-item label="跟进状态">
            <span>{{ props.row.followUpStatus }}</span>
          </el-form-item>
          <el-form-item label="跟进次数">
            <span>{{ props.row.currentCallCount }}</span>
          </el-form-item>
          <el-form-item label="收集人">
            <span>{{ userIdToName(props.row.collectUser) }}</span>
          </el-form-item>
          <el-form-item label="下次跟进日期">
            <span>{{ props.row.nextFollowUpDate}}</span>
          </el-form-item>
          <el-form-item label="最近跟进日期">
            <span>{{ formatDate(props.row.lastFollowUpTime, 'yyyy-MM-dd')}}</span>
          </el-form-item>
        </el-form>
      </template>
      <template slot-scope="scope" slot="followUpUser">
        <el-tag>{{ userIdToName(scope.row.followUpUser) }}</el-tag>
      </template>
      <template slot-scope="scope" slot="collectUser">
        <el-tag>{{ userIdToName(scope.row.collectUser) }}</el-tag>
      </template>
      <template slot-scope="scope" slot="channel">
        <span>{{ channelIdToName(scope.row.channel)}}</span>
      </template>
      <template slot-scope="scope" slot="collectDate">
        <span>{{ formatDate(scope.row.collectDate, 'yyyy-MM-dd')}}</span>
      </template>
      <template slot-scope="scope" slot="nextFollowUpDate">
        <span>{{ scope.row.nextFollowUpDate}}</span>
      </template>
      <template slot-scope="scope" slot="lastFollowUpTime">
        <span>{{ formatDate(scope.row.lastFollowUpTime, 'yyyy-MM-dd')}}</span>
      </template>
      <template slot-scope="scope" slot="idCard">
        <span>{{ scope.row.idCard}}</span>
      </template>
      <template slot-scope="scope" slot="idCardForm">
        <el-input type="text" v-model="idCardFormDate" @blur="ageDate"></el-input>
        <input type="hidden" v-model="user.idCard"/>
      </template>
      <template slot-scope="scope" slot="ageForm">
        <el-input v-model.number="user.age" disabled/>
      </template>
      <template slot-scope="scope" slot="followUpUserForm">
        <el-cascader :options="users" v-model="defaultUser" @change="getNodeData"></el-cascader>
        <input type="hidden" v-model="user.followUpUser"/>
      </template>
      <template slot-scope="scope" slot="label">
        <el-tag v-for="defaultLabel in getLabels(scope.row.label)">{{defaultLabel}}</el-tag>
      </template>
      <template slot-scope="scope" slot="labelForm">
        <input type="hidden" v-model="user.label"/>
        <el-select v-model="selectLabel" collapse-tags  placeholder="请选择" multiple @change="selectedLabel">
          <el-option-group v-for="group in labelData" :label="group.label" :key="group.label">
            <el-option v-for="item in group.children" :label="item.label" :key="item.label"
                       :value="item.value"></el-option>
          </el-option-group>
        </el-select>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-button v-if="qs_intention_customer_upd" type="primary" icon="el-icon-check" size="small" plain
                   @click.stop.safe="handleEdit(scope.row,scope.index,scope.row.groupsort)">编辑
        </el-button>
        <el-button v-if="qs_intention_customer_followup" type="success" icon="el-icon-check" size="small" plain
                   @click.stop.safe="showAddFlowup(scope.row)">跟进
        </el-button>
        <el-button v-if="qs_intention_customer_giveUp" type="danger" icon="el-icon-close" size="small" plain
                   @click.stop.safe="giveUpFlowup(scope.row)">放弃
        </el-button>
      </template>
    </avue-crud>

    <el-dialog title="跟进记录" :visible.sync="grade.box" width="70%" @close="cancel">
      <div class="filter-container">
        <el-button title="新增" type="primary" icon="el-icon-plus" size="small" class="filter-item" @click="addFollow">
          新增
        </el-button>
      </div>
      <el-table :data="callRecordTableData" v-loading="callRecordLoading" element-loading-text="给我一点时间" border fit
                highlight-current-row>
        <el-table-column align="center" label="编号">
          <template scope="scope">
            <span>{{ scope.row.fid }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="跟进日期" width="110">
          <template scope="scope">
            <span>{{ formatDate(scope.row.createTime, 'yyyy-MM-dd')}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="跟进人" width="100">
          <template scope="scope">
            <span>{{ userIdToName(scope.row.createUser)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="意向等级" width="220">
          <template scope="scope">
            <span>{{ setDicData(scope.row.intentionLevel)}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注">
          <template scope="scope">
            <span>{{ scope.row.remark }}</span>
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label="操作" width="100">-->
          <!--<template scope="scope">-->
            <!--<el-button title="编辑" type="primary" icon="el-icon-edit" size="small" @click="editFollow(scope.row)">编辑-->
            <!--</el-button>-->
          <!--</template>-->
        <!--</el-table-column>-->
      </el-table>
      <div v-show="!callRecordLoading" class="pagination-container">
        <el-pagination @size-change="handleCallSizeChange" @current-change="handleCallCurrentChange"
                       :current-page.sync="callListQuery.page"
                       :page-sizes="[10,20,30, 50]" :page-size="callListQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper" :total="callListQuery.total">
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 跟进/放弃跟进模态框 -->
    <el-dialog title="跟进" :visible.sync="displayDialog" @close="cancel('form1')">
      <el-form :model="form1" :rules="rules" ref="form1" label-width="100px">
        <input v-model="form1.fid" hidden/>
        <el-form-item label="姓名" prop="fname">
          <el-input v-model="form1.fname" :disabled="inputDisabled"/>
        </el-form-item>

        <el-form-item label="手机号" prop="tel1">
          <el-input v-model="form1.tel1" :disabled="inputDisabled"/>
        </el-form-item>

        <el-form-item label="跟进次数" prop="currentCallCount">
          <el-input v-model="form1.currentCallCount" :disabled="inputDisabled"/>
        </el-form-item>

        <el-form-item label="意向等级" prop="intentionLevel" v-if="disableLevel === 'put'">
          <el-select v-model="form1.intentionLevel">
            <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="disableLevel == 'put'" label="下次跟进日" prop="nextFollowUpDate">

          <div class="block">
            <el-date-picker
              v-model="form1.nextFollowUpDate"
              type="datetime"
              placeholder="选择日期时间"
              :picker-options="pickerOptions1">
            </el-date-picker>
          </div>
        </el-form-item>

        <el-form-item v-if="disableLevel == 'put'" label="分组">
          <el-cascader change-on-select :options="groupTreeList" v-model="groupsortDefault" @change="getFormGroupSourceNode">
          </el-cascader>
          <input type="hidden" v-model="form1.groupsort"/>
        </el-form-item>

        <!--<el-form-item v-if="disableLevel == 'put'" label="跟进状态" prop="followUpStatus">-->
          <!--<el-radio-group v-model="form1.followUpStatus" @change="selectRadio">-->
            <!--<el-radio :label="1601" :disabled="!redioDisable">跟进中</el-radio>-->
            <!--<el-radio :label="1603" :disabled="redioDisable">跟进成功</el-radio>-->
          <!--</el-radio-group>-->
        <!--</el-form-item>-->

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form1.remark" placeholder="最多输入200个字符" :rows="5"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form1')">取 消</el-button>
        <el-button v-if="disableLevel == 'put'" type="primary" @click="create('form1')">提 交</el-button>
        <el-button v-if="disableLevel == 'del'" type="primary" @click="giveUp('form1')">放 弃</el-button>
      </div>
    </el-dialog>

    <!-- 跟进记录添加修改模态框 -->
    <el-dialog title="编辑" :visible.sync="followUpDialog">
      <el-form :model="followUpForm" :rules="rules" ref="followUpForm" label-width="100px">
        <input v-model="followUpForm.fid" hidden/>

        <el-form-item label="客户姓名" prop="studentId">
          <el-input v-model="followUpForm.studentName" :disabled="inputDisabled"/>
          <input v-model="followUpForm.studentId" hidden/>
        </el-form-item>

        <el-form-item label="创建人" prop="createUser">
          <el-input v-model="followUpForm.createUserName" :disabled="inputDisabled"/>
          <input v-model="followUpForm.createUser" hidden/>
        </el-form-item>

        <el-form-item label="意向等级" prop="intentionLevel">
          <el-select v-model="followUpForm.intentionLevel">
            <el-option v-for="item in levelList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="followUpForm.remark" placeholder="最多输入200个字符" :rows="5"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('followUpForm')">取 消</el-button>
        <el-button type="primary" @click="commitFollowUp('followUpForm')">提 交</el-button>
      </div>
    </el-dialog>

    <!--批量分组-->
    <el-dialog title="批量分组" :visible.sync="dialogBatchUpdate">
      <el-form :model="dialogBatchForm" ref="form" label-width="80px">
        <el-form-item label="分组">
          <el-cascader change-on-select :options="groupTreeList" v-model="dialogBatchForm.groupsort" @change="getGroupSourceNode">
          </el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="batchGroupSubmit">提交</el-button>
        </el-form-item>
      </el-form>

    </el-dialog>



    <!--  客户转移  -->
    <el-dialog title="客户转移" :visible.sync="customerSistribution" @close="cancel">
      <el-form>
        <el-form-item label="选择跟进人" label-width="120px">
          <el-select  v-model="followUpUser" placeholder="请选择跟进人" @change="selectChange">
            <el-option v-for="item in followUpUserList" :label="item.name" :value="item.userId"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sistribution">提 交</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import {addObj, putObj, delObj, addFlowup, checkInformation, batchGrouping} from '@/api/training/training_student'
  import {fetchTree, getNowChannelSource} from '@/api/channelSource'
  import {groupTree, getGroupList} from '@/api/group'
  import tabOption from '@/const/sales/intention_customer_option'
  import {getListByStudent, putFollowUpObj} from '@/api/sales/sales_intention_flowup'
  import {updateToBatch} from '@/api/sales/sales_public_repertory_manage'
  import {fetchList} from '@/api/sales/sales_intention_customer'
  // import {getObjByStudentId} from '@/api/training/training_student_register'
  import {validatenull} from '@/util/validate'
  import {formatDateS, findParent2, isString} from '@/util/util.js'
  import {getDeptUserTree, getUserDeptPath, getIdNameList} from '@/api/user'
  import {remote, initDicList, loadByType} from '@/api/dict'
  import {fetchLabelTree, getNowlabel} from '@/api/label'
  import waves from '@/directive/waves/index.js' // 水波纹指令
  // import {loadByType} from '@/api/dict'
  export default {
    name: 'table_intention_customer',
    directives: {
      waves
    },
    data() {
      return {
        pickerOptions1: {
          shortcuts: [{
            text: '明天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }, {
            text: '两天后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2)
              picker.$emit('pick', date)
            }
          }]
        },
        customerSistribution: false,
        followUpUserList: [],
        followUpUser: '',
        selectLabel: [],
        labelData: undefined,
        labelPageDisplay: false,
        tableSearch: {},
        idCardFormDate: null,
        dialogBatchUpdate: false,
        dialogBatchForm: [],
        tableOption: tabOption, // 表格设置属性
        tableData: [], // 表格的数据
        tableRow: {},
        selectedRows: [],
        formInline: {
          user: null,
          groupsort: null,
          channel: null,
          industryType: [],
          workingArea: [],
          label: null
        },
        groupData: null,
        tableLoading: false,
        tabelObj: {},
        user: {},
        infoForm: {
          channelSource: [],
          intentionLevel: [],
          workingArea: []
        },
        groupTreeList: [],
        groupList: [],
        users: [],
        defaultUser: [],
        listQuery: { //  学员翻页数据
          total: 0, //  总共有多少页
          currentPage: 1, // 当前页数
          pageSize: 10 // 每页显示多少条
        },
        totalPage: null,
        callListQuery: {  // 跟进记录翻页数据
          page: 1,
          limit: 10,
          total: 0,
          student_id: ''
        },
        grade: {
          box: false,
          check: []
        },
        callRecordTableData: [],
        callRecordLoading: false,
        total: null,
        nickName: null,
        displayDialog: false,
        followUpDialog: false,
        sutdentForm: false,
        form1: {
          fid: '',
          fname: '',
          currentCallCount: '',
          // callCount: '',
          tel1: '',
          intentionLevel: '',
          remark: '',
          followUpStatus: '',
          nextFollowUpDate: null,
          groupsort: null
        },
        inputDisabled: true,
        dicType: '',
        levelList: [],
        followUpStatusList: [],
        levelRules: true,
        studentModel: {},
        studentRules: {},
        rules: {
          remark: [
            {
              required: this.levelRules,
              message: '请填写放弃原因',
              trigger: 'blur'
            },
            {
              // min: 0,
              max: 200,
              message: '字符长度不得大于200',
              trigger: 'blur'
            }
          ],
          nextFollowUpDate: [
            {
              required: true,
              message: '请选择下次跟进日期',
              trigger: 'blur'
            }
          ],
          intentionLevel: [
            {
              required: true,
              message: '请选择意向等级',
              trigger: 'blur'
            }
          ]
        },
        disableLevel: '',
        dictMap: [],
        collectUsers: [],
        channelSourceTree: [],
        defaultSource: [],
        groupsortDefault: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        row: undefined,
        followUpForm: {
          studentName: '',
          createUserName: '',
          bizStatus: '',
          createUser: '',
          fid: '',
          intentionLevel: '',
          remark: '',
          studentId: ''
        },
        labelList: undefined,
        // redioDisable: true
      }
    },
    beforeCreate() {
    },
    created() {
      this.infoGroup()
      this.infoDict()
      this.getDicList()
      this.handleList()
      this.initLabelData()
      this.getLabelData()
      this.initUserDic()
      this.getChannelSourceTree()
      this.infoTabelS()
      this.qs_intention_customer_add = this.permissions['qs_intention_customer_add']
      this.qs_intention_customer_transfer = this.permissions['qs_intention_customer_transfer']
      this.qs_intention_customer_upd = this.permissions['qs_intention_customer_upd']
      this.qs_intention_customer_del = this.permissions['qs_intention_customer_del']
      this.qs_intention_customer_followupList = this.permissions['qs_intention_customer_followupList']
      this.qs_intention_customer_followup = this.permissions['qs_intention_customer_followup']
      this.qs_intention_customer_giveUp = this.permissions['qs_intention_customer_giveUp']
    },
    watch: {},
    mounted() {
    },
    computed: {
      ...mapGetters(['permissions', 'menuAll'])
    },
    props: [],
    methods: {
      /**
       *
       *  批量转移客户
       *
       */
      sistribution() {
        updateToBatch(this.selectedRows, this.followUpUser).then(response => {
          this.customerSistribution = false
          this.handleList()
          this.$message({
            showClose: true,
            message: '转移成功',
            type: 'success'
          })
        })
      },
      /**
       *
       * 选择跟进人
       *
       */
      selectChange(val) {
        this.followUpUser = val
      },
      handleTransfer() {
        if (this.selectedRows.length === 0) {
          this.$message({
            showClose: true,
            message: '请选择需要转移的客户',
            type: 'warning'
          })
          return
        }
        this.customerSistribution = true
        for (let i = 0; i < this.selectedRows.length; i++) {
          this.selectedRows[i] = this.formartRow(this.selectedRows[i])
        }
      },
      infoTabelS() {
        getIdNameList().then(response => {
          this.followUpUserList = response.data
          // for (let i = 0; i < response.data.length; i++) {
          //   this.infoTabel.createUser[i] = {0: response.data[i].username, 1: response.data[i].userId}
          // }
        })
      },
      getLabels(labels) {
        if (labels != null) {
          var labelIdArray = labels.split(',')
          if (labelIdArray.length > 0) {
            var labelArray = []
            for (var i = 0; i < this.labelList.length; i++) {
              for (var j = 0; j < labelIdArray.length; j++) {
                if (this.labelList[i].id == labelIdArray[j]) {
                  labelArray.push(this.labelList[i].name)
                }
              }
            }
            return labelArray
          }
        }
      },
      initLabelData() {
        getNowlabel().then(response => {
          this.labelList = response.data
        })
      },
      selectedLabel(data) {
        this.user.label = data
      },
      formLabel(data) {
        this.formInline.label = data
      },
      getLabelData() {
        fetchLabelTree().then(response => {
          this.labelData = response.data
        })
      },
      showLabel() {
        this.labelPageDisplay = true
      },
      commitFollowUp(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            putFollowUpObj(this.followUpForm).then(() => {
              this.followUpDialog = false
              this.handleCalls()
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 2000
              })
            })
          } else {
            return false
          }
        })
      },
      editFollow(row) {
        this.followUpForm = row
        this.followUpForm.studentName = this.tableRow[0].fname
        this.followUpForm.createUserName = this.userIdToName(this.followUpForm.createUser)
        this.initLevelList(row)
        this.followUpDialog = true
      },
      addFollow() {
        this.showAddFlowup(this.row)
      },
      infoDict() {
        loadByType('intention_level').then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.infoForm.intentionLevel[i] = {0: response.data[i].label, 1: response.data[i].value}
          }
        })
        loadByType('working_area').then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.infoForm.workingArea[i] = {0: response.data[i].label, 1: response.data[i].value}
          }
        })
      },
      getGroupsort(value) {
        for (let i = 0; i < this.groupList.length; i++) {
          if (this.groupList[i][0] === value) {
            return this.groupList[i][1]
          }
        }
      },
      // selectRadio(val) {
      //   this.form1.followUpStatus = val
      // },
      ageDate() {
        var value = this.idCardFormDate
        value += ''
        if (value === null || value.trim() === '' || value.trim() === 'null') {
          this.user.idCard = null
          return null
        } else if (!(value.length === 15 || value.length === 18)) {
          this.user.idCard = null
          return null
        } else if (!(((value.substr(0, value.length - 1) - 1) + 1) === (value.substr(0, value.length - 1) - 0))) {
          this.user.idCard = null
          return null
        } else {
          var age = 0
          if (value.length === 15) {
            if (!(((value.substr(0, value.length) - 1) + 1) === (value.substr(0, value.length) - 0))) {
              this.user.idCard = null
              return null
            }
            age = this.ageData('19' + value.substr(6, 6))
          } else {
            var a = value.substr(6, 8)
            age = this.ageData(a)
          }
          if (!Number(age)) {
            this.user.idCard = null
            return null
          } else {
            this.user.age = age
          }
        }
        this.user.idCard = this.idCardFormDate
        return null
      },
      ageData(value) {
        var beginDate = new Date(value.substr(0, 4) + '-' + value.substr(4, 2) + '-' + value.substr(6, 2)).getTime()
        var newDate = new Date(new Date().getTime() - beginDate) + ''
        return formatDateS(new Date(newDate), 'yyyy-MM-dd hh:mm:ss').substr(0, 4) - 1970
      },
      channelIdToName(channelId) {
        return findParent2(this.channelSourceTree, channelId - 0)
      },
      getNowChannelSource(sourceId) {
        getNowChannelSource(sourceId).then(response => {
          this.defaultSource = response.data
        })
      },
      getChannelSourceTree() {
        fetchTree().then(response => {
          this.channelSourceTree = response.data
        })
      },
      getGroupsortId(value) {
        const groupId = [value]
        let parentId = value
        while (!(Number(parentId) === 0) || parentId.length < 20) {
          for (let i = 0; i < this.groupList.length; i++) {
            if (this.groupList[i][0] === parentId) {
              parentId = this.groupList[i][2]
              groupId[groupId.length] = this.groupList[i][2]
              continue
            }
          }
        }
        return groupId.reverse()
      },
      infoGroup() {
        groupTree().then(response => {
          this.groupTreeList = response.data
        })
        getGroupList().then(response => {
          for (let i = 0; i < response.data.length; i++) {
            this.groupList[i] = {0: response.data[i].id, 1: response.data[i].name, 2: response.data[i].parentId}
          }
        })
      },
      formatDate(date, fromat) {
        if (date != null) {
          return formatDateS(new Date(date), fromat)
        } else {
          return '-'
        }
      },
      fillForm1Data(row) {
        this.form1.fid = row.fid
        this.form1.currentCallCount = row.currentCallCount
        this.form1.tel1 = row.tel1
        this.form1.intentionLevel = row.intentionLevel
        this.form1.fname = row.fname
      },
      p(s) {
        return s < 10 ? '0' + s : s
      },
      giveUp(formName) {
        this.form1.followUpStatus = '1602'
        if (this.form1.remark === '') {
          this.$message({
            title: '提示',
            message: '请填写放弃原因',
            type: 'warning',
            duration: 2000
          })
          return
        }
        this.$refs[formName].validate(valid => {
          addFlowup(this.form1).then(() => {
            this.displayDialog = false
            this.handleList()
            this.$notify({
              title: '完成',
              message: '放弃成功',
              type: 'success',
              duration: 2000
            })
          })
          this.$refs[formName].resetFields()
        })
      },
      giveUpFlowup(row) {
        this.displayDialog = true
        this.disableLevel = 'del'
        this.fillForm1Data(row)
      },
      cancel(formName) {
        this.followUpDialog = false
        this.displayDialog = false
        this.followUpUser = ''
        this.row = undefined
        this.customerSistribution = false
        this.$refs[formName].resetFields()
      },
      create(formName) {
        const set = this.$refs
        set[formName].validate(valid => {
          if (valid) {
            // this.form1.followUpStatus = '1601'
            for (var i = 0; i < this.levelList.length; i++) {
              if (this.levelList[i].label === this.form1.intentionLevel) {
                this.form1.intentionLevel = this.levelList[i].value
              }
            }
            this.form1.nextFollowUpDate = this.formatDate(this.form1.nextFollowUpDate, 'yyyy-MM-dd hh:mm:ss')
            addFlowup(this.form1).then(() => {
              this.displayDialog = false
              this.handleList()
              if (this.row !== undefined) {
                this.getCallList(this.row)
              }
              this.$notify({
                title: '成功',
                message: '提交成功',
                type: 'success',
                duration: 2000
              })
              this.$refs[formName].resetFields()
            })
          } else {
            return false
          }
        })
      },
      initLevelList(row) {
        this.dicType = 'intention_level'
        remote(this.dicType).then(response => {
          this.levelList = response.data
          for (var i = 0; i < response.data.length; i++) {
            if (row.intentionLevel === response.data[i].value) {
              this.form1.intentionLevel = response.data[i].label
              this.followUpForm.intentionLevel = response.data[i].label
            }
          }
        })
      },
      showAddFlowup(row) {
        // getObjByStudentId(row.fid).then(response => {
        //   if (response.data.data.length > 0 && response.data.data[0].isPay == 1) {
        //     this.redioDisable = false
        //   } else {
        //     this.redioDisable = true
        //   }
        // })
        this.displayDialog = true
        this.disableLevel = 'put'
        this.fillForm1Data(row)
        this.initLevelList(row)
        this.form1.nextFollowUpDate = row.nextFollowUpDate
        this.groupsortDefault = this.getGroupsortId(row.groupsort)
        this.form1.groupsort = this.groupsortDefault[this.groupsortDefault.length - 1]
        this.dicType = 'follow_up'
        remote(this.dicType).then(response => {
          this.followUpStatusList = response.data
          for (var i = 0; i < response.data.length; i++) {
            if (row.followUpStatus === response.data[i].label) {
              this.form1.followUpStatus = response.data[i].sort
            }
          }
        })
      },
      initUserDic() {
        getDeptUserTree().then(response => {
          this.users = response.data
        })
      },
      getGroupSourceNode(data) {
        this.user.groupsort = data[data.length - 1]
      },
      getFormGroupSourceNode(data) {
        this.form1.groupsort = data[data.length - 1]
      },
      getSourceNode(data) {
        this.user.channel = data[data.length - 1]
      },
      getNodeData(data) {
        this.user.followUpUser = data[data.length - 1]
      },
      setDicData(value) {
        for (let i = 0; i < this.dictMap.length; i++) {
          for (var key in this.dictMap[i]) {
            if (key === value) {
              return this.dictMap[i][key]
            } else if (value === this.dictMap[i][key]) {
              return key
            }
          }
        }
      },
      getDicList() {
        initDicList().then(response => {
          this.dictMap = response.data
        })
      },
      userIdToName(userId) {
        return findParent2(this.users, userId)
      },
      /**
       * 获取用户组织路径
       * @param userId 用户ID
       */
      getUserDeptPath(userId) {
        getUserDeptPath(userId).then(response => {
          this.defaultUser = response.data
        })
      },
      /**
       * @title 刷新数据
       *
       **/
      handlerefreshChange(page) {
        this.handleList(true)
        // this.$notify({
        //   message: `刷新数据成功`,
        //   type: 'success'
        // })
      },
      /**
       * @title 权限更新
       *
       **/
      handleGradeUpdate() {
        this.tabelObj.check = [].concat(this.grade.check)
        this.tabelObj = {}
        this.grade.check = []
        this.grade.box = false
      },
      /**
       * @title 权限选择
       *
       **/
      handleGradeCheckChange(data, checked, indeterminate) {
        if (checked) {
          this.grade.check.push(data.id)
        } else {
          this.grade.check.splice(this.grade.check.indexOf(data.id), 1)
        }
      },
      handleRowEdit() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要编辑的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleEdit(this.tableRow[0], -1)
      },
      handleEdit(row, index) {
        this.$refs.crud.rowEdit(row, index)
        this.formartRow(row)
        row.collectUser = this.collectUsers[index]
      },
      formartRow(row) {
        if (row.label != null && isString(row.label)) {
          if (row.label.length > 1) {
            var splitLabel = row.label.split(',')
            for (var i = 0; i < splitLabel.length; i++) {
              this.selectLabel.push(splitLabel[i] - 0)
            }
          } else {
            this.selectLabel.push(row.label - 0)
          }
        }
        if (!validatenull(row.bizStatus)) {
          row.bizStatus = this.setDicData(row.bizStatus)
        }
        if (!validatenull(row.followUpUser)) {
          this.getUserDeptPath(row.followUpUser)
        }
        if (!validatenull(row.channel)) {
          this.getNowChannelSource(row.channel)
        }
        if (!validatenull(row.groupsort)) {
          this.groupsortDefault = this.getGroupsortId(row.groupsort)
          this.user.groupsort = this.groupsortDefault[this.groupsortDefault.length - 1]

          // let groupList = this.getGroupsortId(row.groupsort)
          // this.groupsortDefault = groupList[this.groupsortDefault.length - 1]
          // this.user.groupsort = this.groupsortDefault
        }
        row.followUpUser = this.user.followUpUser
        row.channel = this.user.channel
        row.groupsort = this.user.groupsort
        for (let i = 0; i < this.dictMap.length; i++) {
          for (var key in this.dictMap[i]) {
            switch (this.dictMap[i][key]) {
              case row.workingType:
                row.workingType = key
                break
              case row.jobType:
                row.jobType = key
                break
              case row.workingArea:
                row.workingArea = key
                break
              case row.homeArea:
                row.homeArea = key
                break
              case row.intentionLevel:
                row.intentionLevel = key
                break
              case row.followUpStatus:
                row.followUpStatus = key
                break
            }
          }
        }
        return row
      },
      /**
       * @title 打开权限
       */
      handleGrade(row, index) {
        this.$store.dispatch('GetMenuAll').then(data => {
          this.grade.box = true
          this.tabelObj = row
          this.grade.check = this.tabelObj.check
        })
      },
      /**
       * @title 导出excel
       *
       **/
      handleExport() {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['username', 'name']
          const filterVal = ['username', 'name']
          const list = this.tableData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel(tHeader, data, this.filename)
        })
      },
      /**
       * @title 页面改变值
       *
       **/
      handleCurrentChange(val) {
        this.listQuery.currentPage = val
        this.handleList()
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.handleList()
      },
      onSubmit() {
        var queryParams = {
          'condition': this.formInline.user,
          'groupsort': this.formInline.groupsort,
          'intention_level': this.formInline.industryType,
          'working_area': this.formInline.workingArea,
          'label': this.formInline.label
        }
        if (this.formInline.label != null && this.formInline.label.length > 0) {
          queryParams.label = this.formInline.label.join(',')
        }
        if (this.formInline.industryType != null && this.formInline.industryType.length > 0) {
          queryParams.intention_level = this.formInline.industryType.join(',')
        }
        if (this.formInline.workingArea != null && this.formInline.workingArea.length > 0) {
          queryParams.working_area = this.formInline.workingArea.join(',')
        }
        if (this.formInline.channel != null) {
          var i = this.formInline.channel.length - 1
          queryParams.channel = this.formInline.channel[i]
        } else {
          queryParams.channel = null
        }
        if (this.formInline.groupsort != null) {
          var groupsortLength = this.formInline.groupsort.length - 1
          queryParams.groupsort = this.formInline.groupsort[groupsortLength]
        } else {
          queryParams.groupsort = null
        }
        var params = Object.assign({}, this.page, queryParams)
        fetchList(params).then(response => {
          this.tableData = response.data.records
          this.listQuery = {
            total: response.data.total,
            page: response.data.current,
            limit: response.data.size
          }
          this.tableLoading = false
        })
      },
      resetForm() {
        this.selectLabel = []
        this.formInline = {
          user: null,
          groupsort: [],
          channel: [],
          industryType: [],
          workingArea: [],
          label: []
        }
      },
      batchGroupSubmit() {
        if (!(this.tableRow != null && this.tableRow.length > 0)) {
          this.$notify({
            showClose: true,
            message: '请至少选择一行数据',
            type: 'error'
          })
          return
        }
        var fids = []
        var group = this.dialogBatchForm.groupsort[this.dialogBatchForm.groupsort.length - 1]
        for (var i = 0; i < this.tableRow.length; i++) {
          fids[i] = this.tableRow[i].fid
        }
        batchGrouping(fids, group).then(() => {
          this.dialogBatchUpdate = false
          this.handleList()
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
        })
      },
      /**
       * @title 搜索按钮回掉
       *
       **/
      handleSearchChange(form) {
        this.tableSearch = form
        this.tableLoading = true
        var queryParams = {
          'home_area': this.tableSearch.homeArea,
          'fname': this.tableSearch.fname,
          'tel1': this.tableSearch.tel1,
          'tel2': this.tableSearch.tel1,
          'id_card': this.tableSearch.idCard,
          'page': this.listQuery.currentPage,
          'limit': this.listQuery.pageSize
        }
        var params = Object.assign({}, queryParams)
        fetchList(params).then(response => {
          this.tableData = response.data.records
          this.listQuery = {
            total: response.data.total
          }
          this.tableLoading = false
        })
      },
      /**
       * @title 打开新增窗口
       * @detail 调用crud的handleadd方法即可
       *
       **/
      handleAdd() {
        // this.sutdentForm = true
        this.$refs.crud.rowAdd()
      },
      /**
       * @title 选中第几行
       * @param row 选中那几行数据
       * @detail 调用crud的toggleSelection方法即可
       *
       **/
      toggleSelection(row) {
        this.$refs.crud.toggleSelection(row)
      },
      /**
       * @title 获取数据
       * @detail 赋值为tableData表格即可
       *
       **/
      handleList(boo) {
        this.tableLoading = true
        fetchList({
          page: this.listQuery.currentPage,
          limit: this.listQuery.pageSize
        }).then(response => {
          this.tableData = response.data.records
          this.formatList()
          this.listQuery = {
            currentPage: response.data.current,
            pageSize: response.data.size,
            total: response.data.total
          }
          this.totalPage = response.data.total
          this.tableLoading = false
          if (boo) {
            this.$notify({
              message: `刷新数据成功`,
              type: 'success'
            })
          }
        })
      },
      formatList() {
        for (var i = 0; i < this.tableData.length; i++) {
          this.collectUsers.push(this.tableData[i].collectUser)
          this.tableData[i].workingType = this.setDicData(this.tableData[i].workingType)
          this.tableData[i].homeArea = this.setDicData(this.tableData[i].homeArea)
          this.tableData[i].bizStatus = this.setDicData(this.tableData[i].bizStatus)
          this.tableData[i].followUpStatus = this.setDicData(this.tableData[i].followUpStatus)
          this.tableData[i].intentionLevel = this.setDicData(this.tableData[i].intentionLevel)
          this.tableData[i].jobType = this.setDicData(this.tableData[i].jobType)
          this.tableData[i].workingArea = this.setDicData(this.tableData[i].workingArea)
          // this.tableData[i].collectUser = this.userIdToName(this.tableData[i].collectUser)
        }
      },
      /**
       * @title 当前选中的数据
       * @param val 选中的值
       *
       **/
      handleSelectionChange(val) {
        this.tableRow = val
        this.selectedRows = val
        // this.$notify({
        //   showClose: true,
        //   message: JSON.stringify(val),
        //   type: 'success'
        // })
      },
      /**
       * @title 数据添加
       * @param row 为当前的数据
       * @param done 为表单关闭函数
       *
       **/
      handleSave(row, done) {
        done()
        checkInformation(row.tel1).then(response => {
          if (!response.data.data) {
            this.$message({
              title: '提示',
              message: '手机号1已存在 ！',
              type: 'warning',
              duration: 2000
            })
            return
          }
          checkInformation(row.tel2).then(response => {
            if (row.tel2.trim() !== '') {
              if (!response.data.data) {
                this.$message({
                  title: '提示',
                  message: '手机号2已存在 ！',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
            }
            checkInformation(row.idCard).then(response => {
              if (!response.data.data) {
                this.$message({
                  title: '提示',
                  message: '身份证号已存在 ！',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
              if (row.label != null && row.label.length > 0) {
                row.label = row.label.join(',')
              }
              addObj(Object.assign({}, row)).then(() => {
                this.dialogFormVisible = false
                this.handleList()
                this.$message({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              })
            })
          })
        })
      },
      /**
       * @title 行双击
       * @param row 为当前的数据
       * @param event 事件
       *
       **/
      handleRowDBLClick(row, event) {
        this.handleEdit(row, event.path[1].rowIndex)
        // this.$notify({
        //   showClose: true,
        //   message: '双击',
        //   type: 'success'
        // })
      },

      /**
       * @title 行单机
       * @param row 为当前的数据
       * @param event 事件
       * @param column 列
       *
       **/
      handleRowClick(row, event, column) {
        this.$notify({
          showClose: true,
          message: '单机',
          type: 'success'
        })
      },
      handleRowDel() {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要删除的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        this.handleDel(this.tableRow[0], -1)
      },
      /**
       * @title 数据删除
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       *
       **/
      handleDel(row, index) {
        this.$confirm(`是否确认删除序号为${row.name}`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delObj(row).then(response => {
            this.dialogFormVisible = false
            this.handleList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      /**
       * @title 批量分组
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       **/
      batchUpdate() {
        this.dialogBatchUpdate = true
        this.dialogBatchForm.groupsort = [1]
      },
      /**
       * @title 数据更新
       * @param row 为当前的数据
       * @param index 为当前更新数据的行数
       * @param done 为表单关闭函数
       *
       **/
      handleUpdate(row, index, done) {
        checkInformation(row.tel1).then(response => {
          if (!response.data.data && (response.data.msg - 0) !== row.fid) {
            this.$notify({
              title: '提示',
              message: '手机号1已存在 ！',
              type: 'warning',
              duration: 2000
            })
            return
          }
          checkInformation(row.tel2).then(response => {
            if (!response.data.data && (response.data.msg - 0) !== row.fid) {
              this.$notify({
                title: '提示',
                message: '手机号1已存在 ！',
                type: 'warning',
                duration: 2000
              })
              return
            }
            checkInformation(row.idCard).then(response => {
              if (!response.data.data && (response.data.msg - 0) !== row.fid) {
                this.$notify({
                  title: '提示',
                  message: '身份证号已存在 ！',
                  type: 'warning',
                  duration: 2000
                })
                return
              }
              this.selectLabel = []
              this.handleEdit(row, index)
              if (row.label != null && row.label.length > 0 && !isString(row.label)) {
                row.label = row.label.join(',')
              }
              putObj(row).then(data => {
                this.handleList()
                this.tableData.splice(index, 1, Object.assign({}, row))
                this.$message({
                  showClose: true,
                  message: '修改成功',
                  type: 'success'
                })
                done()
              })
            })
          })
        })
      },
      /**
       * @title 表单关闭前处理
       * @param done
       *
       **/
      boxhandleClose(done) {
        this.defaultUser = []
        this.selectLabel = []
        // this.$notify({
        //   showClose: true,
        //   message: '表单关闭前处理事件',
        //   type: 'success'
        // })
        done()
      },
      boxhandleOpen(show) {
        this.$notify({
          showClose: true,
          message: '表单打开前处理事件',
          type: 'success'
        })
        show()
      },
      /**
       *  跟进记录切换每页多少条数据
       * @param val
       */
      handleCallSizeChange(val) {
        this.callListQuery.limit = val
        this.getCallList(this.tableRow[0])
      },
      /**
       *  跟进记录翻页
       * @param val
       */
      handleCallCurrentChange(val) {
        this.callListQuery.page = val
        this.getCallList(this.tableRow[0])
      },
      /**
       *  跟进记录查询
       */
      handleCalls() {
        this.row = this.tableRow[0]
        this.getCallList(this.tableRow[0])
      },
      getCallList(row) {
        if (validatenull(this.tableRow)) {
          this.$notify({
            showClose: true,
            message: '请选择一行要查看的数据',
            type: 'error'
          })
          return false
        } else if (this.tableRow.length > 1) {
          this.$notify({
            showClose: true,
            message: '请选择一行数据，不要选择多行',
            type: 'error'
          })
          return false
        }
        // this.$store.dispatch(
        //   getListByStudent,
        //   Object.assign({}, {'studentId': this.tableRow.studentId}, {callListQuery: `${this.tablePage}`})
        // ).then(data => {
        //   this.tableData = data.tableData
        //   this.total = data.total
        //   this.tableLoading = false
        // })

        this.grade.box = true
        this.callListQuery.student_id = row.fid
        getListByStudent(this.callListQuery).then(data => {
          this.callRecordTableData = data.data.records
          this.callListQuery = {
            total: data.data.total,
            limit: data.data.size,
            page: data.data.current
          }
          this.tableLoading = false
        })
      },
      tableRowClassName({row, rowIndex}) {
        if (row.warningType === 1) {
          return 'warning-row'
        } else if (row.warningType === 2) {
          return 'success-row'
        }
        return ''
      }
    }
  }
</script>

<style lang="scss" scoped>
  .table-container {
    padding: 8px 10px;
  }

  .table-header {
    margin-bottom: 10px;
    & > .el-button {
      padding: 12px 25px;
    }
  }

  .demo-table-expand {
    font-size: 0;
  }

  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }

  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
</style>


<style>
  .el-table .warning-row {
    background: #d682aa;
  }

  .el-table .success-row {
    background: #0bbab3;
  }
</style>

